import datetime

import jwt
from django.conf import settings

EXP_TIME_OF_HOUR = 24


def generate_token(name, ip):
    key = settings.SECRET_KEY
    payload = {
        'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=EXP_TIME_OF_HOUR),
        'iat': datetime.datetime.utcnow(),
        'data': {'account': name, 'ip': ip}  # 添加自定义的数据，保存在data中
    }
    token = str(jwt.encode(payload, key, algorithm='HS256'), encoding='utf-8')
    return token


def decode_token(token):
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
        if payload:
            return True, payload
        else:
            raise ValueError("token为空")
    except Exception as e:
        return False, ""


def get_account(payload):
    return payload['data']['account']
